package com.example.his.api.front.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.annotation.SaIgnore;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.map.MapUtil;
import com.example.his.api.common.R;
import com.example.his.api.config.sa_token.StpCustomerUtil;
import com.example.his.api.constant.SystemEnum;
import com.example.his.api.front.controller.form.CustomerLoginForm;
import com.example.his.api.front.controller.form.SendSmsForm;
import com.example.his.api.front.controller.form.UpdateCustomerForm;
import com.example.his.api.front.service.CustomerService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

/**
 * @author huixh
 */
@RestController
@RequestMapping("/front/customer")
public class CustomerController {
    @Resource
    private CustomerService customerService;

    @SaIgnore
    @PostMapping("/sendSmsCode")
    public R sendSmsCode(@RequestBody @Valid SendSmsForm form) {
        boolean result = customerService.sendSmsCode(form.getTel());
        String msg = result ? "发送成功" : "发送失败";
        return R.ok(msg).put("result", result);
    }



    @PostMapping("/login")
    public R login(@RequestBody @Valid CustomerLoginForm form) {
        HashMap<String, Object> result = customerService.login(form.getTel(), form.getCode());
        Boolean res = MapUtil.getBool(result, "result");
        String msg = MapUtil.getStr(result, "msg");
        R r = R.ok(msg).put("result", res);
        if (res) {
            Integer id = MapUtil.getInt(result, "id");
            StpCustomerUtil.login(id, SystemEnum.WEB.getType());
            String tokenValue = StpCustomerUtil.getTokenValue();
            r.put("token", tokenValue);
        }
        return r;
    }

    @GetMapping("/logout")
    @SaCheckLogin(type = StpCustomerUtil.TYPE)
    public R logout() {
        StpCustomerUtil.logout(SystemEnum.WEB.getType());
        return R.ok("退出成功");
    }

    @GetMapping("/checkLogin")
    public R checkLogin() {
        boolean login = StpCustomerUtil.isLogin();
        return R.ok().put("result", login);
    }


    @SaCheckLogin(type = StpCustomerUtil.TYPE)
    @GetMapping("/searchSummary")
    public R searchSummary() {
        Integer id = StpCustomerUtil.getLoginIdAsInt();
        Map<String, Object> searchSummary = customerService.searchSummary(id);
        return R.ok().put("result", searchSummary);
    }

    @SaCheckLogin(type = StpCustomerUtil.TYPE)
    @PostMapping("/update")
    public R update(@RequestBody @Valid UpdateCustomerForm customerForm) {
        int id = StpCustomerUtil.getLoginIdAsInt();
        Map<String, Object> map = BeanUtil.beanToMap(customerForm);
        map.put("id", id);
        boolean result = customerService.updateCustomer(map);

        if (!result) {
            return R.resultFail();
        }
        return R.resultOk();
    }



}
